define(["jquery", "easy-admin","vue", "ckeditor"], function ($, ea, Vue, ckeditor) {
    var form = layui.form;
    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: 'member.wechatKeyword/index?miniapp_id='+CONFIG.MINIAPP_ID,
        add_url: 'member.wechatKeyword/add?miniapp_id='+CONFIG.MINIAPP_ID,
        edit_url: 'member.wechatKeyword/edit?miniapp_id='+CONFIG.MINIAPP_ID,
        delete_url: 'member.wechatKeyword/del?miniapp_id='+CONFIG.MINIAPP_ID,
        export_url: 'member.wechatKeyword/export?miniapp_id='+CONFIG.MINIAPP_ID,
        modify_url: 'member.wechatKeyword/modify?miniapp_id='+CONFIG.MINIAPP_ID,
        add_material: 'member.wechatKeyword/addMaterial?miniapp_id='+CONFIG.MINIAPP_ID,
        add_keys: 'member.wechatKeyword/addKeys?miniapp_id='+CONFIG.MINIAPP_ID
    };

    var Controller = {

        index: function () {
            ea.table.render({
                init: init,
                cols: [[
                    {type: 'checkbox'},
                    {field: 'id', title: '序号',searchOp: '='},
                    {field: 'is_mp', title: '公众号', templet: function (d) {
                        return d.is_mp ? '是':'否'
                        }, search: false},
                    //{field: 'is_miniapp', title: '小程序',search: 'select', selectList: ["否","是"], tips: '是|否', templet: ea.table.switch, search: false},
                    {field: 'type', title: '类型', templet: ea.table.text},
                    {field: 'type', title: '预览', templet: '#preview'},
                    {field: 'keys', title: '关键字'},
                    {field: 'content', title: '内容'},
                    {field: 'status', title: '状态',search: 'select', selectList: ["禁用","使用中"], tips: '使用中|禁用', templet: ea.table.switch},
                    {field: 'create_at', title: '创建时间', search: false},
                    {
                        width: 250,
                        title: '操作',
                        templet: ea.table.tool,
                    },
                ]],
                toolbar: ['refresh', 'delete',
                    [{
                        text: '添加回复规则',
                        url: init.add_keys,
                        method: 'open',
                        auth: 'add',
                        class: 'layui-btn layui-btn-normal layui-btn-sm',
                        icon: 'fa fa-plus ',
                        extend: 'data-full="true"',
                    }]],
            });
            ea.listen();
        },
        add: function () {
            ea.listen();
        },
        edit: function () {
            ea.listen();
        },
        addMaterial: function () {
            window.vm = new Vue({
                el: '#NewsEditor',
                data: function () {
                    return {
                        currentIndex:0,
                        articles: [],
                        list: [],
                        item: {
                            title: '新建图文',
                            author: '管理员',
                            content: '文章内容',
                            read_num: 0,
                            local_url: '/static/manage/images/image.png',
                            style: "background-image:url('/static/manage/images/image.png')",
                            digest: '',
                            content_source_url:'',
                            show_cover_pic:false,
                            active:true
                        },
                        isHide: true
                    }
                },
                methods: {
                    onRefresh: function apply(list) {
                        if (list.length < 1) {list.push({
                            title: '新建图文', author: '管理员', content: '文章内容',
                            read_num: 0, local_url: '/static/manage/images/image.png',
                            digest: '',
                            content_source_url:'',
                            show_cover_pic:false,
                        })}else {
                            //手动设置编辑器的内容
                            CKEDITOR.instances.content.setData(list[0]['content']);
                        }
                        for (var i in list) {
                            list[i].active = false;
                            list[i].style = "background-image:url('" + list[i].local_url + "')";
                        }
                        this.list = list;
                        this.item = this.list[0];
                        this.setItemValue('active', true);
                        this.isHide = false;
                        this.setItem(0);//处理初始化图片显示不正常
                    },
                    setItemValue: function (name, value) {
                        this.item[name] = value;
                        this.item.style = "background-image:url('" + this.item.local_url + "')";
                    },
                    setItem: function (index, $event) {
                       // $event.stopPropagation();
                        this.currentIndex = index;
                        //if ($form.find('.validate-error').size() > 0) return 0;
                        if (CKEDITOR.instances.content.getData().length < 1) {
                            ea.msg.error('文章内容不能为空，请输入文章内容！');
                        }
                        for (var i in this.list) if (parseInt(i) !== parseInt(index)) {
                            this.list[i].active = false;
                        } else {
                            this.item.content = CKEDITOR.instances.content.getData();
                            this.item = this.list[i];
                            CKEDITOR.instances.content.setData(this.item.content);
                            this.setItemValue('active', true);
                        }
                        this.$nextTick(function () {
                            form.render("checkbox");//很重要的绑定
                            $("input[name='local_url']").trigger("input");
                        })

                    },
                    // submit: function () {
                    //     $vali.checkAllInput();
                    //     if ($form.find('.validate-error').size() > 0) {
                    //         return $.msg.tips('表单验证不成功，请输入需要的内容！');
                    //     }
                    //     $rootScope.item.content = editor.getData();
                    //     var data = [];
                    //     for (var i in $rootScope.list) data.push({
                    //         id: $rootScope.list[i].id,
                    //         title: $rootScope.list[i].title,
                    //         author: $rootScope.list[i].author,
                    //         digest: $rootScope.list[i].digest,
                    //         content: $rootScope.list[i].content,
                    //         read_num: $rootScope.list[i].read_num,
                    //         local_url: $rootScope.list[i].local_url,
                    //         show_cover_pic: $rootScope.list[i].show_cover_pic ? 1 : 0,
                    //         content_source_url: $rootScope.list[i].content_source_url,
                    //     });
                    //     $.form.load('/wechat/news/add.html?spm=m-56-60-62&output=json', {data: data}, "post");
                    // },
                    addItem: function () {
                        if (this.list.length > 7) {
                            ea.msg.error('最多允许增加7篇文章哦！');
                        }
                        this.list.push({
                            title: '新建图文',
                            author: '管理员',
                            content: '文章内容',
                            read_num: 0,
                            local_url: '/static/manage/images/image.png',
                            style: "background-image:url('/static/manage/images/image.png')",
                            digest: '',
                            content_source_url:'',
                            show_cover_pic:false,
                        });
                    },
                },
                mounted: function() {
                    var _this =this;
                    var option = {
                        url: editUrl,
                        data:{
                            output: 'json'
                        }
                    }
                    ea.request.get(option, function (ret) {
                        if(ret.data.data.length != 0) _this.articles = ret.data.data.articles;
                        _this.onRefresh(_this.articles);
                    });
                },
                watch: {
                    'item.local_url': function (newVal, oldVal) {
                        this.item.style = "background-image:url('" + newVal + "')";
                    }
                }
            });
            form.on('checkbox(show_cover_pic)', function (data) {
                //console.log(data.elem.checked); //是否被选中，true或者false
                //console.log(data.value); //复选框value值，也可以通过data.elem.value得到
               vm.item.show_cover_pic = data.elem.checked;
                vm.list[vm.currentIndex].show_cover_pic = data.elem.checked;
            });
            ea.listen(function (data) {
                //在提交之前把当前页面内的content赋给当前数组下标内的content
                vm.list[vm.currentIndex]['content'] = CKEDITOR.instances.content.getData();
                var dataArray = [];
                for (var i in vm.list) dataArray.push({
                    id: vm.list[i].id,
                    title: vm.list[i].title,
                    author: vm.list[i].author,
                    digest: vm.list[i].digest,
                    content: vm.list[i].content,
                    read_num: vm.list[i].read_num,
                    local_url: vm.list[i].local_url,
                    show_cover_pic: vm.list[i].show_cover_pic ? 1 : 0,
                    content_source_url: vm.list[i].content_source_url,
                });
                return {data:dataArray};
            });
            //监听上传成功后给local_url赋值
            $('body').on('input','[name="local_url"]',function () {
                vm.item.local_url = $('[name="local_url"]').val();
            })
            // var editor;
            // var $form = $('form[name="news"]');
            // var $vali = $form.vali().data('validate');
            //
            // var app = angular.module("NewsEditor", []).run(callback);
            // angular.bootstrap(document.getElementById(app.name), [app.name]);
            //
            // function callback($rootScope) {
            //     $rootScope.list = [];
            //     $rootScope.item = {};
            //     // ea.request.get({url:'/manage/member.wechatKeyword/addMaterial'},function (ret) {
            //     //     return $rootScope.$apply(function () {
            //     //         apply((ret.data || {articles: []}).articles || []);
            //     //     }), false;
            //     // })
            //     // $.form.load('/manage/member.wechatKeyword/addMaterial', {output: 'json'}, 'get', function (ret) {
            //     //     return $rootScope.$apply(function () {
            //     //         apply((ret.data || {articles: []}).articles || []);
            //     //     }), false;
            //     // });
            //     apply(({articles: []}).articles || []);
            //     function apply(list) {
            //         if (list.length < 1) list.push({
            //             title: '新建图文', author: '管理员', content: '文章内容',
            //             read_num: 0, local_url: '__ROOT__/static/theme/img/image.png',
            //         });
            //         for (var i in list) {
            //             list[i].active = false;
            //             list[i].style = "background-image:url('" + list[i].local_url + "')";
            //         }
            //         $rootScope.list = list;
            //         $rootScope.item = $rootScope.list[0];
            //         $rootScope.setItemValue('active', true);
            //         $('.layui-card-body.layui-hide').removeClass('layui-hide');
            //         setTimeout(function () {
            //             if (editor) editor.destroy();
            //             editor = window.createEditor('[name="content"]');
            //             editor.setData($rootScope.item.content);
            //             $vali.checkAllInput();
            //         }, 100);
            //     }
            //
            //     $rootScope.upItem = function (index, $event) {
            //         $event.stopPropagation();
            //         var tmp = [], cur = $rootScope.list[index];
            //         if (index < 1) return false;
            //         for (var i in $rootScope.list) {
            //             (parseInt(i) === parseInt(index) - 1) && tmp.push(cur);
            //             (parseInt(i) !== parseInt(index)) && tmp.push($rootScope.list[i]);
            //         }
            //         apply(tmp);
            //     };
            //     $rootScope.dnItem = function (index, $event) {
            //         $event.stopPropagation();
            //         var tmp = [], cur = $rootScope.list[index];
            //         if (index > $rootScope.list.length - 2) return false;
            //         for (var i in $rootScope.list) {
            //             (parseInt(i) !== parseInt(index)) && tmp.push($rootScope.list[i]);
            //             (parseInt(i) === parseInt(index) + 1) && tmp.push(cur);
            //         }
            //         apply(tmp);
            //     };
            //     $rootScope.delItem = function (index, $event) {
            //         $event.stopPropagation();
            //         var list = $rootScope.list, temp = [];
            //         for (var i in list) (parseInt(i) !== parseInt(index)) && temp.push(list[i]);
            //         apply(temp);
            //     };
            //     $rootScope.setItem = function (index, $event) {
            //         $event.stopPropagation();
            //         $vali.checkAllInput();
            //         if ($form.find('.validate-error').size() > 0) return 0;
            //         if (editor.getData().length < 1) {
            //             return $.msg.tips('文章内容不能为空，请输入文章内容！');
            //         }
            //         for (var i in $rootScope.list) if (parseInt(i) !== parseInt(index)) {
            //             $rootScope.list[i].active = false;
            //         } else {
            //             $rootScope.item.content = editor.getData();
            //             $rootScope.item = $rootScope.list[i];
            //             editor.setData($rootScope.item.content);
            //             $rootScope.setItemValue('active', true);
            //         }
            //     };
            //     $rootScope.setItemValue = function (name, value) {
            //         $rootScope.item[name] = value;
            //         $rootScope.item.style = "background-image:url('" + $rootScope.item.local_url + "')";
            //     };
            //     $rootScope.addItem = function () {
            //         if ($rootScope.list.length > 7) {
            //             return $.msg.tips('最多允许增加7篇文章哦！');
            //         }
            //         $rootScope.list.push({
            //             title: '新建图文',
            //             author: '管理员',
            //             content: '文章内容',
            //             read_num: 0,
            //             local_url: '/static/manage/images/image.png',
            //             style: "background-image:url('/static/manage/images/image.png')"
            //         });
            //     };
            //     $rootScope.submit = function () {
            //         $vali.checkAllInput();
            //         if ($form.find('.validate-error').size() > 0) {
            //             return $.msg.tips('表单验证不成功，请输入需要的内容！');
            //         }
            //         $rootScope.item.content = editor.getData();
            //         var data = [];
            //         for (var i in $rootScope.list) data.push({
            //             id: $rootScope.list[i].id,
            //             title: $rootScope.list[i].title,
            //             author: $rootScope.list[i].author,
            //             digest: $rootScope.list[i].digest,
            //             content: $rootScope.list[i].content,
            //             read_num: $rootScope.list[i].read_num,
            //             local_url: $rootScope.list[i].local_url,
            //             show_cover_pic: $rootScope.list[i].show_cover_pic ? 1 : 0,
            //             content_source_url: $rootScope.list[i].content_source_url,
            //         });
            //         $.form.load('/wechat/news/add.html?spm=m-56-60-62&output=json', {data: data}, "post");
            //     };
            //     $('[name="local_url"]').on('change', function (value) {
            //         value = this.value;
            //         $rootScope.$apply(function () {
            //             $rootScope.setItemValue('local_url', value);
            //         });
            //     });
            // }

        },
        select: function (){
            require(['jquery.masonry'], function (Masonry) {
                $('.news-container.layui-hide').removeClass('layui-hide');
                var msnry = new Masonry($('.news-container').get(0), {itemSelector: '.news-item', columnWidth: 0});
                msnry.layout();
                // 事件处理
                $('.news-item').on('mouseenter', '.news-container', function () {
                    $(this).addClass('active');
                }).on('mouseleave', '.news-container', function () {
                    $(this).removeClass('active');
                });
                // 外部选择器
                var seletor = seletorEle;
                if (seletor) {
                    $('[data-news-id]').on('click', function () {
                        parent.$(seletor).val($(this).attr('data-news-id')).trigger('change');
                        parent.layer.close(parent.layer.getFrameIndex(window.name))
                    });
                }
                // 分页事件处理
                $('body').off('change', '.pagination-trigger select').on('change', '.pagination-trigger select', function () {
                    var urls = this.options[this.selectedIndex].getAttribute('data-url').split('#');
                    urls.shift();
                    window.location.href = urls.join('#');
                }).off('click', '[data-open]').on('click', '[data-open]', function () {
                    window.location.href = this.getAttribute('data-open');
                });
            });
        },
        materialList: function () {
            $('body').on('mouseenter', '.news-item', function () {
                $(this).find('.news-tools').removeClass('layui-hide');
            }).on('mouseleave', '.news-item', function () {
                $(this).find('.news-tools').addClass('layui-hide');
            });

            require(['jquery.masonry'], function (Masonry) {
                var item = document.querySelector('#news-box');
                var msnry = new Masonry(item, {itemSelector: '.news-item', columnWidth: 0});
                msnry.layout();
                $('body').on('click', '[data-news-del]', function () {
                    var that = this;
                    ea.msg.confirm('确定要删除图文吗？', function () {
                        ea.request.post({url:delUrl,data:{id:that.getAttribute('data-news-del')}},function (ret) {
                            ea.msg.success(ret.msg);
                            window.location.reload();
                        },function (ret) {
                            ea.msg.error(ret.msg);
                        })
                    });
                });
            });
            ea.listen();
        },
        addKeys: function () {
            var $body = $('body');
            // 刷新预览显示
            function showReview(params, src) {
                if (params['type'] === 'news') {
                    src = 'previewNews?id=_id_'.replace('_id_', params.content);
                } else {
                    var str =params.type;
                    src = 'preview_type_?'.replace('_type_', str.trim().toLowerCase().replace(str[0], str[0].toUpperCase())) + $.param(params || {});
                }
                $('#phone-preview').attr('src', src);
            }
            var i =0;
            $body.on('input','[name="image_url"]',function () {
                i++;
                if(i >1) $('[name="image_url"]').trigger("change");
            })
            $body.on('input','[name="voice_url"]',function () {
                $(this).trigger("change");
            })

            $body.off('change', '[name="news_id"]').on('change', '[name="news_id"]', function () {
                // 图文显示预览
                showReview({type: 'news', content: this.value});
            }).off('change', '[name="content"]').on('change', '[name="content"]', function () {
                // 文字显示预览
                showReview({type: 'text', content: this.value});
            }).off('change', '[name="image_url"]').on('change', '[name="image_url"]', function () {
                // 图片显示预览
                showReview({type: 'image', content: this.value});
            }).off('change', '[name="voice_url"]').on('change', '[name="voice_url"]', function () {
                // 语音显示预览
                showReview({type: 'voice', url: this.value});
            });

            // 音乐显示预览
            var musicSelector = '[name="music_url"],[name="music_title"],[name="music_desc"],[name="music_image"]';
            $body.on('input',musicSelector,function () {
                $(this).trigger("change");
            })
            $body.off('change', musicSelector).on('change', musicSelector, function () {
                var params = {type: 'music'}, $parent = $(this).parents('form');
                params.url = $parent.find('[name="music_url"]').val();
                params.desc = $parent.find('[name="music_desc"]').val();
                params.title = $parent.find('[name="music_title"]').val();
                params.image = $parent.find('[name="music_image"]').val();
                showReview(params);
            });

            // 视频显示预览
            var videoSelector = '[name="video_title"],[name="video_url"],[name="video_desc"]';
            $body.on('input',videoSelector,function () {
                $(this).trigger("change");
            })
            $body.off('change', videoSelector).on('change', videoSelector, function () {
                var params = {type: 'video'}, $parent = $(this).parents('form');
                params.url = $parent.find('[name="video_url"]').val();
                params.desc = $parent.find('[name="video_desc"]').val();
                params.title = $parent.find('[name="video_title"]').val();
                showReview(params);
            });

            // 默认类型事件
            $body.off('click', 'input[name=type]').on('click', 'input[name=type]', function () {
                var value = $(this).val(), $form = $(this).parents('form');
                if (value === 'customservice') value = 'text';
                var $current = $form.find('[data-keys-type="' + value + '"]').removeClass('layui-hide');
                $form.find('[data-keys-type]').not($current).addClass('layui-hide');
                switch (value) {
                    case 'news':
                        return $('[name="news_id"]').trigger('change');
                    case 'text':
                    case 'customservice':
                        return $('[name="content"]').trigger('change');
                    case 'image':
                        return $('[name="image_url"]').trigger('change');
                    case 'video':
                        return $('[name="video_url"]').trigger('change');
                    case 'music':
                        return $('[name="music_url"]').trigger('change');
                    case 'voice':
                        return $('[name="voice_url"]').trigger('change');
                }
            });

            // 默认事件触发
            $('input[name=type]:checked').map(function () {
                $(this).trigger('click');
            });
            ea.listen(function (data) {
                delete data.file;
                return data;
            });
            if(subscribeType != ''){
                $("input[name='type'][value='" + subscribeType + "']").next('.layui-form-radio').click();
                $("input[name='type'][value='" +  subscribeType + "']").trigger('click');
            }


        },
        subscribe: function () {
            this.addKeys();
        },
        previewView: function () {
            ea.listen();
        }
    };
    return Controller;
});